package com.king01.aspect;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.king01.annotation.LogAnnotation;
import com.king01.entity.Log;
import com.king01.entity.Staff;
import com.king01.entity.SysOperLog;
import com.king01.service.SysOperLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author：张梓康
 * @date：Created in 2023/10/16 20:08
 * @description：
 * @modified By：
 * @version:
 */

@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysOperLogService sysOperLogService;
    @Pointcut("@annotation(com.king01.annotation.LogAnnotation)")
    private void mypoint(){}

    @Around("mypoint()")
    public Object my(ProceedingJoinPoint joinPoint){
//        添加日志-日志对象
        SysOperLog sysOperLog = new SysOperLog();
        sysOperLog.setOperTime(new Date());
        Staff staff = (Staff) session.getAttribute("staff");
        sysOperLog.setOperName(staff.getStaffname());
        sysOperLog.setRequestMethod(request.getMethod());
        sysOperLog.setOperUrl(request.getRequestURI());
        sysOperLog.setOperIp(request.getRemoteAddr());
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] args = joinPoint.getArgs();
        sysOperLog.setOperParam(JSON.toJSONString(args));
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        sysOperLog.setBusinessType(annotation.business_type());
        sysOperLog.setMethod(method.getName());
        try {
            Object proceed = joinPoint.proceed();
            sysOperLog.setJsonResult(JSON.toJSONString(proceed));
            sysOperLog.setStatus(1);
            return proceed;
        } catch (Throwable e) {
            sysOperLog.setStatus(0);
            throw new RuntimeException("操作错误");
        }finally {
//            添加日志
            sysOperLogService.insert(sysOperLog);
        }
    }

}
